<template>
  <view class="container">
    <view class="card" :class="{ flip: isFlipped }">
      <!-- 登录表单 -->
      <view class="card-front">
        <u-form @submit.prevent="handleLogin">
          <u-form-item>
            <view class="title">LINK</view>
          </u-form-item>
          <u-form-item>
            <u-input
              class="underline-input"
              placeholder="请输入邮箱"
              type="text"
              v-model="loginEmail"
              clearable
              autoBlur
            ></u-input>
          </u-form-item>
          <u-form-item>
            <u-input
              class="underline-input"
              placeholder="请输入密码"
              type="password"
              v-model="loginPassword"
              clearable
              autoBlur
            ></u-input>
          </u-form-item>
          <u-button 
            class="btn"
            type="primary" 
            @click="handleLogin">登录</u-button>
          <view class="flipCardText" @click="flipCard()">没有账号？现在去注册-></view>
		  <u-form-item>
			  <image src="../../static/img/DuoLaAMeng.png"
			  style="margin: auto; width: 500rpx;height: 280rpx;"></image>
		  </u-form-item>
        </u-form>
      </view>

      <!-- 注册表单 -->
      <view class="card-back">
        <u-form @submit.prevent="handleRegister">
			<u-form-item>
				<view class="title">LINK 连接世界 连接你我</view>
			</u-form-item>
          <u-form-item>
            <u-input
              class="underline-input"
              placeholder="请输入邮箱"
              type="text"
              v-model="registerEmail"
              clearable
              autoBlur
            ></u-input>
          </u-form-item>
          <u-form-item>
            <u-input
              class="underline-input"
              placeholder="请输入验证码"
              type="text"
              v-model="verificationCode"
              clearable
              autoBlur
            ></u-input>
            <u-button
              class="getVerificationCodeBtn"
              @click="getVerificationCode"
              :disabled="isCountingDown"
            >
              {{ isCountingDown ? countdown + '秒' : '获取验证码' }}
            </u-button>
          </u-form-item>
          <u-form-item>
            <u-input
              class="underline-input"
              placeholder="请输入密码"
              type="password"
              v-model="registerPassword"
              autoBlur
            ></u-input>
          </u-form-item>
          <u-form-item>
            <u-input
              class="underline-input"
              placeholder="请再次输入密码"
              type="password"
              v-model="isRegisterPassword"
              autoBlur
            ></u-input>
          </u-form-item>
          <u-button
            class="btn"
            type="primary" 
            @click="handleRegister">注册</u-button>
          <view class="flipCardText" @click="flipCard">注册完毕，现在去登录-></view>
        </u-form>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      loginEmail: '',
      loginPassword: '',
      registerEmail: '',
      registerPassword: '',
      verificationCode: '',
      isRegisterPassword: '',
      isFlipped: false,
      countdown: 300, // 倒计时时间（秒）
      isCountingDown: false ,// 是否在倒计时中
	  deviceId:'',
	  countdownConfig:300,
	  uid:'',
	  token:''
    };
  },
  methods: {
    handleLogin() {
      if (!this.validateEmail(this.loginEmail)) {
		uni.showToast({
			title:'邮箱格式不正确',
			icon:'error',
			duration:2000
		});
        return;
      }
      console.log('登录邮箱:', this.loginEmail);
      console.log('登录密码:', this.loginPassword);
	  uni.showLoading({
	  	title:"loading",
		mask:true
	  })
	  this.getSystemInfo();
	  uni.request({
	  	url:this.baseUrl+'/login',
		method:'POST',
		data:{
			data:{
				email:this.loginEmail,
				password:this.loginPassword,
				currentDevice:this.deviceId	
			},
			msgType:'login'
		},
		header: {
			'Content-Type': 'application/json' // 如果需要以JSON格式发送数据
		},
		success: (res) => {
			console.log('POST 请求成功', res.data);
			
			if(res.data.code==1){
				//console.log(res.data.data.token);
				this.uid=res.data.data.UserId;
				this.token=res.data.data.token;
				uni.setStorageSync('UID',res.data.data.UserId);
				uni.setStorageSync('token',res.data.data.token);
				this.getUserAvatar();
				this.$websocket.connect(res.data.data.UserId,res.data.data.token);
				uni.hideLoading();
				uni.showToast({
					title:'登录成功',
					icon:'success',
					duration:2000
				});
					uni.reLaunch({
						url:'/pages/home/home'
					}).catch(err=>{
						console.error("Navigation error:", err);
					});
				
			}else{
				uni.hideLoading();
				uni.showToast({
					title:res.data.msg,
					icon:'none',
					duration:2000
				});
			}
		},
		fail: (err) => {
			uni.hideLoading();
			console.log('POST 请求失败', err);
		}
	  })
	  
    },
    handleRegister() {
      if (!this.validateEmail(this.registerEmail)) {
        console.log('邮箱格式不正确');
		uni.showToast({
			title:'邮箱格式不正确',
			icon:'error',
			duration:2000
		});
        return;
      }
      if (this.registerPassword.length < 6) {
        console.log('密码长度至少为6位');
		uni.showToast({
			title:'密码长度至少为6位',
			icon:'error',
			duration:2000
		});
        return;
      }
      if (this.registerPassword === this.isRegisterPassword) {
        console.log('注册邮箱:', this.registerEmail);
        console.log('注册密码:', this.registerPassword);
		uni.showLoading({
			title:"loading",
			mask:true
		})
		uni.request({
			url:this.baseUrl+'/register',
			method:'POST',
			data:{
				data:{
					email:this.registerEmail,
					password:this.registerPassword,
					code:this.verificationCode
				},
				msgType:'register'
			},
			header: {
				'Content-Type': 'application/json' // 如果需要以JSON格式发送数据
			},
			success: (res) => {
				uni.hideLoading();
				//console.log(res);
				if(res.data.code==1){
					uni.showToast({
						title:res.data.data,
						icon:'none',
						duration:2000
					});
					this.verificationCode='';
					this.registerPassword='';
					this.isRegisterPassword='';
					this.flipCard();
				}else if(res.data.code==0){
					uni.showToast({
						title:res.data.msg,
						icon:'none',
						duration:2000
					});
				}else{
					uni.showToast({
						title:'系统错误，请联系我们',
						icon:'none',
						duration:2000
					});
				}
				
			},
			fail: (err) => {
				uni.hideLoading();
				console.log(err);
			}
		})
      } else {
		uni.showToast({
			title:'两次输入的密码不一致',
			icon:'error',
			duration:2000
		});
		return;
      }
    },
    validateEmail(email) {
      const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return re.test(email);
    },
    getVerificationCode() {
          if (this.isCountingDown) return; // 如果在倒计时中，则不允许获取验证码
          if (!this.validateEmail(this.registerEmail)) {
            uni.showToast({
              title: '邮箱格式不正确',
              icon: 'error',
              duration: 2000
            });
            return;
          }
          console.log('注册邮箱:', this.registerEmail, '获取验证码');
          uni.showLoading({
            title: 'Loading',
            mask: true
          });
          uni.request({
            url: this.baseUrl + '/registerGetEmailVerifyCode',
            method: 'POST',
            data: {
              data: {
                email: this.registerEmail
              },
              msgType: 'getEmailVerifyCode'
            },
            header: {
              'Content-Type': 'application/json'
            },
            success: (res) => {
              uni.hideLoading();
              if (res.data.code == 1) {
                uni.showToast({
                  title: res.data.data,
                  icon: 'success',
                  duration: 2000
                });
                this.startCountdown(); // 启动倒计时
              } else {
                uni.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  duration: 2000
                });
              }
            },
            fail: (err) => {
              uni.hideLoading();
              uni.showToast({
                title: err,
                icon: 'none',
                duration: 2000
              });
            }
          });
        },
    
        startCountdown() {
          this.isCountingDown = true;
          this.countdown = this.countdownConfig; // 重置倒计时为配置值
    
          const interval = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(interval);
              this.isCountingDown = false; // 倒计时结束
            }
          }, 1000);
        },
    
        flipCard() {
          this.isFlipped = !this.isFlipped;
          if (this.isFlipped) {
            const nowTime = new Date();
            const lastGetEmailVerifyCodeTime = uni.getStorageSync("lastGetEmailVerifyCodeTime");
    
            // 确保上次获取验证码的时间存在
            if (lastGetEmailVerifyCodeTime) {
              const timeDifference = (nowTime - new Date(lastGetEmailVerifyCodeTime)) / 1000; // 转换为秒
              if (timeDifference < this.countdownConfig) {
                this.countdown = this.countdownConfig - Math.floor(timeDifference);
                this.startCountdown(); // 启动倒计时
              }
            }
          }
        },
	getSystemInfo(){
		const systemInfo=uni.getSystemInfoSync();
		console.log(systemInfo);
		this.deviceId=systemInfo.deviceId;
	},
	getUserAvatar(){
		uni.request({
		        url: this.baseUrl+'/getUserAvatar',
		        method: 'POST',
		        data: {
					data:{
						userId:this.uid
					},
					msgType:'getUserAvatar'
		        },
		        header: {
					'Content-Type': 'application/json',
					'token':this.token,
					'uid':this.uid
		        },
		        success: (res) => {
					console.log(res);
					if(res.data.code==1){
						const userAvatar=res.data.data.imgType+'base64,'+res.data.data.userAvatar;
						uni.setStorageSync("userAvatar"+this.uid,userAvatar);
					}
		        },
		        fail: (err) => {
					console.error('请求失败:', err);
		        }
		});
	},
  },
  mounted() {
	
  },
  onShow() {
  	
  }
};
</script>

<style>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.card {
  width: 350px;
  height: 450px;
  perspective: 1000px;
  position: relative;
}

.card-front,
.card-back {
  width: 100%;
  height: 100%;
  position: absolute;
  backface-visibility: hidden;
  transition: transform 1s;
  border: 2rpx solid #dfdfdf;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.card-front {
  z-index: 2;
}

.card-back {
  transform: rotateY(180deg);
}

.card.flip .card-front {
  transform: rotateY(180deg);
}

.card.flip .card-back {
  transform: rotateY(0);
}

.u-input {
  margin-left: 15px;
  margin-right: 15px;
  border: none;
  border-bottom: 1px solid #ff6a00 !important; /* 默认边框颜色 */
  outline: none;
  transition: border-color 0.3s; /* 添加过渡动画 */
}


.btn {
  background: linear-gradient(45deg, #ff6a00, #ff8a3d); /* 渐变背景 */
  color: #fff; /* 文字颜色 */
  font-size: 16px; /* 字体大小 */
  margin-top: 20rpx;
  width: 300rpx !important;
  margin-left: auto !important;
  padding: 10rpx; /* 增加内边距 */
  border: none !important; /* 去掉边框 */
  border-radius: 8px !important; /* 圆角 */
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2) !important; /* 添加阴影 */
  transition: background-color 0.3s, transform 0.2s; /* 添加过渡效果 */
}

.btn:hover {
  background: linear-gradient(45deg, #ff8a3d, #ff6a00); /* 悬停渐变效果 */
  transform: translateY(-2rpx); /* 悬停时稍微抬起 */
}

.getVerificationCodeBtn {
  background-color: #f1f1f1; /* 背景色 */
  color: #303133; /* 文字颜色 */
  font-size: 14px; /* 字体大小 */
  margin-left: 20rpx !important;
  margin-right: 20rpx !important;
  width: 200rpx !important;
  padding: 8rpx !important; /* 增加内边距 */
  border: 1px solid #d3d3d3 !important; /* 边框 */
  border-radius: 5px !important; /* 圆角 */
  transition: background-color 0.3s, transform 0.2s; /* 添加过渡效果 */
}

.getVerificationCodeBtn:hover {
  background-color: #e0e0e0; /* 悬停时变色 */
  transform: translateY(-2rpx); /* 悬停时稍微抬起 */
}

.flipCardText {
	width: 100%;
    color: #007BFF; /* 蓝色字体 */
    font-size: 16px; /* 字体大小 */
    margin-top: 20px; /* 向下靠拢，调整此值以控制距离 */
    text-align: center; /* 居中对齐 */
}

.title {
    font-size: 24px; /* 字体大小 */
    font-weight: bold; /* 字体加粗 */
    color: #333; /* 字体颜色 */
    text-align: center; /* 居中对齐 */
    margin: auto; /* 自动外边距 */
	margin-top: 45rpx;
    padding: 10px; /* 内边距 */
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1); /* 字体阴影 */
    font-family: 'Arial', sans-serif; /* 字体类型 */
    transition: color 0.3s, transform 0.3s; /* 过渡效果 */
}

.title:hover {
    color: #ff6a00; /* 鼠标悬停时的颜色 */
    transform: scale(1.05); /* 鼠标悬停时放大 */
}

</style>
